package cn.com.fssg.platform.base.handler.impl.cl.jiesuan;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import cn.com.fssg.platform.biz.ExtendUtil;
import cn.com.fssg.platform.modules.system.entity.SysUser;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @className: ClInstitutionCtl
 * @description: TODO 类描述
 * @author: xzm
 * @date: 2025/10/20
 **/
@Component
public class ClInstitutionCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
    //@Autowired
    //private NamedParameterJdbcTemplate jdbcTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String type = jsonObject.getString("type");
        //id查询
        if(StringUtils.equals(type, "0")){
            //查询
            String id = jsonObject.getString("id");
            String querySql = "select id,org_name,org_type,fuju_list_json,dept_id,org_service_cat,org_service_type,org_quyu," +
                    "org_phone,org_tel,org_shengyuan,org_hourse_area,org_shizi,org_lxr,org_address,org_jieshao " +
                    "from cl_org ";
            Map<String,Object> map = new HashMap<>();
            map.put("id",id);
            if(StringUtils.isNotBlank(id)){
                querySql += " where id =:id";
            }
            Map<String,Object> queryMap = jdbcTemplate.queryForMap(querySql, map);
            if(StringUtils.isNotBlank(Objects.toString(queryMap.get("fuju_list_json"),""))){
                JSONObject fujuJson = JSONObject.parseObject(Objects.toString(queryMap.get("fuju_list_json"),""));
                queryMap.put("item",fujuJson.getString("item"));
                queryMap.put("fuju_list_json",fujuJson.getString("fjmc"));
            }
            return queryMap;
        } else if(StringUtils.equals(type, "1")){
            String loginname = jsonObject.getString("org_phone");
            //判断账号是否存在
            String querySql = "select count(id) from pxone.su_user where loginname =:loginname";
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put("loginname",loginname);
            Map<String,Object> queryUserMap = jdbcTemplate.queryForMap(querySql, queryMap);
            if(StringUtils.equals(queryUserMap.get("count").toString(), "1")){
                return new Exception("添加的账号已存在");
            }
            //添加用户
            saveUser(jsonObject);
            //添加机构数据
            int flag = saveDept(jsonObject);
            return flag;
        }else if(StringUtils.equals(type, "2")){
            //修改机构信息
            Map<String,Object> map = new HashMap<>();
            String id = jsonObject.getString("id");
            map.put("id",id);
            map.put("org_type",jsonObject.getString("org_type"));
            map.put("org_phone",jsonObject.getString("org_phone"));
            map.put("org_tel",jsonObject.getString("org_tel"));
            map.put("org_service_cat",jsonObject.getString("org_service_cat"));
            map.put("org_service_type",jsonObject.getString("org_service_type"));
            map.put("org_shengyuan",jsonObject.getString("org_shengyuan"));
            map.put("org_hourse_area",jsonObject.getLong("org_hourse_area"));
            map.put("org_shizi",jsonObject.getString("org_shizi"));
            map.put("org_lxr",jsonObject.getString("org_lxr"));
            map.put("org_address",jsonObject.getString("org_address"));
            map.put("org_jieshao",jsonObject.getString("org_jieshao"));

            if(StringUtils.isNotBlank(jsonObject.getString("fuju_list_json"))){
                JSONObject fujuJson = new JSONObject();
                fujuJson.put("fjmc",jsonObject.getString("fuju_list_json"));
                fujuJson.put("item",jsonObject.getString("item"));
                map.put("fuju_list_json",fujuJson.toString());
            }
            int count = updateDatabase(map,"cl_org");
            return count;
        }else if(StringUtils.equals(type, "3")){

            if(StringUtils.isBlank(jsonObject.getString("id"))){
                return new Exception("未选中需要删除的机构");
            }
            //删除
            String batch = jsonObject.getString("batch");
            Map<String,Object> map = new HashMap<>();
            //单次删除
            if(StringUtils.equals(batch, "Y")){
                map.put("id",jsonObject.getString("id"));
                map.put("del_flag",1);
                return updateDatabase(map,"cl_org");
            }
            //批量删除
            if(StringUtils.equals(batch, "N")){
                jsonObject.getJSONArray("id").forEach(item->{
                    map.put("id",item);
                    map.put("del_flag",1);
                    updateDatabase(map,"cl_org");
                });
            }
            return batch;

        }else if(StringUtils.equals(type, "4")){
            //机构用户管理-添加用户
            JSONObject json = new JSONObject();
            json.put("password",jsonObject.getString("org_password"));
            json.put("dept_id",jsonObject.getString("dept_id"));
            json.put("phone",jsonObject.getString("org_phone"));
            json.put("realname",jsonObject.getString("org_name"));
            json.put("role_code",jsonObject.getString("role_code"));
            return saveUser(json);
        }
        return null;
    }

    /** 添加机构数据 */
    public int saveDept(JSONObject jsonObject) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",BizUtil.cur().getSnowflakeIdStr());
        map.put("org_name",jsonObject.getString("org_name"));
        map.put("org_type",jsonObject.getString("org_type"));
        map.put("org_quyu",jsonObject.getString("org_quyu"));
        map.put("org_phone",jsonObject.getString("org_phone"));
        map.put("org_tel",jsonObject.getString("org_tel"));
        map.put("org_service_cat",jsonObject.getString("cjr_service_cat"));
        map.put("org_service_type",jsonObject.getString("cjr_service_type"));
        map.put("org_shengyuan",jsonObject.getString("org_shengyuan"));
        map.put("org_shizi",jsonObject.getString("org_shizi"));
        map.put("org_password",jsonObject.getString("org_password"));
        map.put("org_hourse_area",jsonObject.getLong("org_hourse_area"));
        map.put("org_lxr",jsonObject.getString("org_lxr"));
        map.put("org_address",jsonObject.getString("org_address"));
        map.put("org_jieshao",jsonObject.getString("org_jieshao"));
        if(StringUtils.isNotBlank(jsonObject.getString("fuju_list_json"))){
            JSONObject fujuJson = new JSONObject();
            fujuJson.put("fjmc",jsonObject.getString("fuju_list_json"));
            fujuJson.put("item",jsonObject.getString("item"));
            map.put("fuju_list_json",fujuJson.toString());
        }
        map.put("create_by",BizUtil.cur().curUserId());
        map.put("create_time",new Date());
        map.put("update_by",BizUtil.cur().curUserId());
        map.put("update_time",new Date());
        map.put("del_flag","0");
        String roleSql = "select * from pxone.su_depart where id =:id";
        Map<String,Object> queryRoleMap = new HashMap<>();
        queryRoleMap.put("id",jsonObject.getString("dept_id"));
        Map<String,Object> queryRole = jdbcTemplate.queryForMap(roleSql, queryRoleMap);
        //json.put("org_status",queryRole.get("status"));
        map.put("parent_dept_id",queryRole.get("parent_id"));
        map.put("org_status","0");
        map.put("dept_id",jsonObject.getString("dept_id"));
        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        map.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO cl_org (%s) VALUES (%s)",
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        int count = jdbcTemplate.update(sql, map);
        return count;
    }
    /** 添加用户 */
    public boolean saveUser(JSONObject jsonObject) throws Exception {
        //添加
        JSONObject json = new JSONObject();
        String id = BizUtil.cur().getSnowflakeIdStr();
        //String id = "769187002133110784";
        json.put("id",id);
        String password = jsonObject.getString("password");
        json.put("realname", jsonObject.getString("realname"));
        json.put("loginname", jsonObject.getString("phone"));
        json.put("phone", jsonObject.getString("phone"));
        json.put("password", password);

        //json.put("sex", jsonObject.getLong("sex"));
        json.put("updateBy", BizUtil.cur().curUserId());
        json.put("createBy", BizUtil.cur().curUserId());
        json.put("updateTime", new Date());
        json.put("createTime", new Date());
        json.put("status", 1);
        json.put("del_flag", 0);
        json.put("user_identity", 1);
        json.put("create_time", new Date());

        String roleSql = "select * from pxone.su_role where role_code =:role_code";
        Map<String,Object> queryRoleMap = new HashMap<>();
        queryRoleMap.put("role_code",jsonObject.getString("role_code"));
        Map<String,Object> queryRole = jdbcTemplate.queryForMap(roleSql, queryRoleMap);
        json.put("selectedroles",queryRole.get("id"));
        json.put("selecteddeparts",jsonObject.getString("dept_id"));
        json.put("tecjrlhh","tecjrlhh");
        return ExtendUtil.cur().addUser(json);
    }

    /** 修改机构 */
    public int updateDatabase(Map<String, Object> param, String tableName) {
        List<String> fields = new ArrayList<>();
        param.forEach((k, v) -> {
            if (v != null && !"id".equals(k)) {
                fields.add(k + " = :" + k);
            }
        });

        String sql = String.format("UPDATE %s SET %s WHERE id = '%s'",
                tableName,
                String.join(", ", fields),
                param.get("id")
        );
        return jdbcTemplate.update(sql, param);
    }

}
